import UploadImage from '@/components/Upload';
import {
  MedicineCategoryAPI,
  addMedicineAPI,
  delMedicineAPI,
  loadMedicDataAPI,
  modifyMedicineAPI,
} from '@/services/medicine';
import { dalImg } from '@/utils/tools';
import { DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons';
import {
  ModalForm,
  PageContainer,
  ProForm,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';
//@ts-ignore
import { FormattedMessage } from '@umijs/max';
import { Button, Popconfirm, Space } from 'antd';
import { useEffect, useRef, useState } from 'react';

function Medicine() {
  //展示上传图片地址
  const [imageUrl, setImageUrl] = useState<string>();
  //药品分类数据
  const [category, setCategory] = useState([]);
  const [myForm] = ProForm.useForm();
  const [isShow, setIsShow] = useState(false);
  const [editID, setEditID] = useState('');
  const actionRef = useRef<any>();
  //模态框关闭后需要清除的数据
  useEffect(() => {
    if (!isShow) {
      setEditID('');
      setImageUrl('');
    }
  }, [isShow]);
  useEffect(() => {
    MedicineCategoryAPI().then((res: any) => {
      // console.log(res.data.list);
      setCategory(
        res.data.list.map((item: { name: string; id: string }) => {
          return {
            label: item.name,
            value: item.id,
          };
        }),
      );
    });
  }, []);
  return (
    <PageContainer>
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        bordered
        request={loadMedicDataAPI}
        toolBarRender={() => {
          return [
            <Button
              onClick={() => {
                setIsShow(true);
              }}
              size="small"
              type="primary"
              key={crypto.randomUUID()}
            >
              <PlusOutlined />
              <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
            </Button>,
          ];
        }}
        columns={[
          {
            title: '序号',
            width: '60px',
            align: 'center',
            search: false,
            render(value, item, index) {
              // console.log(item);
              return index + 1;
            },
          },
          {
            title: '药品',
            width: '100px',
            align: 'center',
            dataIndex: 'name',
          },
          {
            title: '主图',
            width: '120px',
            align: 'center',
            search: false,
            // eslint-disable-next-line @typescript-eslint/no-unused-vars
            render(value, item, index) {
              return (
                <img width="65px" height="65px" src={dalImg(item.image)} alt={item.name}></img>
              );
            },
          },
          {
            title: '功效',
            align: 'center',
            ellipsis: true,
            search: false,
            dataIndex: 'desc',
          },
          {
            title: '分类',
            width: '110px',
            align: 'center',
            search: false,
            // eslint-disable-next-line @typescript-eslint/no-unused-vars
            render(value, item, index) {
              return <>{item.category?.name}</>;
            },
          },
          {
            title: '操作',
            search: false,
            width: '80px',
            align: 'center',
            // eslint-disable-next-line @typescript-eslint/no-unused-vars
            render(value, item, index) {
              return (
                <Space>
                  <Button
                    shape="circle"
                    type="primary"
                    size="small"
                    onClick={() => {
                      setIsShow(true);
                      setEditID(item.id);
                      setImageUrl(dalImg(item.image));
                      myForm.setFieldsValue(item);
                    }}
                    icon={<EditOutlined />}
                  />

                  <Popconfirm
                    title="删除"
                    description="是否确认删除？"
                    onConfirm={() => {
                      delMedicineAPI(item.id).then(() => {
                        actionRef.current.reload();
                      });
                    }}
                    okText="确认"
                    cancelText="取消"
                  >
                    <Button
                      shape="circle"
                      type="primary"
                      size="small"
                      danger
                      icon={<DeleteOutlined />}
                    />
                  </Popconfirm>
                </Space>
              );
            },
          },
        ]}
      ></ProTable>
      <ModalForm
        form={myForm}
        width="650px"
        open={isShow}
        onOpenChange={setIsShow}
        modalProps={{ maskClosable: false, destroyOnClose: true }}
        onFinish={async (v) => {
          // console.log(v);
          if (editID) {
            await modifyMedicineAPI(editID, { ...v, image: imageUrl });
          } else {
            await addMedicineAPI({ ...v, image: imageUrl });
          }
          actionRef.current.reload();
          setIsShow(false);
        }}
      >
        <ProForm.Item>
          <ProFormText
            name="name"
            width="md"
            label="药品名"
            rules={[{ required: true, message: '请输入药名' }]}
          />
        </ProForm.Item>
        <ProForm.Item label="主图">
          <UploadImage imageUrl={imageUrl} setImageUrl={setImageUrl} />
        </ProForm.Item>
        <ProFormSelect
          width="md"
          options={category}
          name="medicineCategoryId"
          label="分类"
        ></ProFormSelect>
        <ProForm.Item>
          <ProFormTextArea name="desc" width="lg" label="功效" />
        </ProForm.Item>
      </ModalForm>
    </PageContainer>
  );
}

export default Medicine;
